package com.kingdee.shr.custom.handler.deptworklist;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.ui.ModelMap;

import com.kingdee.bos.BOSException;
import com.kingdee.bos.Context;
import com.kingdee.bos.util.BOSUuid;
import com.kingdee.bos.workflow.WfException;
import com.kingdee.bos.workflow.service.EnactmentServiceProxy;
import com.kingdee.eas.base.permission.UserInfo;
import com.kingdee.eas.custom.deptseasonworklist.DeptWorklistInfo;
import com.kingdee.eas.framework.CoreBaseInfo;
import com.kingdee.eas.hr.base.HRBillStateEnum;
import com.kingdee.eas.hr.emp.PersonPositionInfo;
import com.kingdee.eas.util.app.ContextUtil;
import com.kingdee.eas.util.app.DbUtil;
import com.kingdee.jdbc.rowset.IRowSet;
import com.kingdee.shr.affair.web.util.SHRBillUtil;
import com.kingdee.shr.base.syssetting.app.filter.HRFilterUtils;
import com.kingdee.shr.base.syssetting.context.SHRContext;
import com.kingdee.shr.base.syssetting.exception.SHRWebException;
import com.kingdee.shr.base.syssetting.exception.ShrWebBizException;
import com.kingdee.shr.base.syssetting.web.handler.EditHandler;
import com.kingdee.shr.base.syssetting.web.json.JSONUtils;
import com.kingdee.util.DateTimeUtils;
import com.kingdee.util.StringUtils;

/**
 * 
 * Title: DeptWorklistEditHandler Description: 部门季度工作目标清单Handler
 * 
 * @author saisai_cheng Email:854296216@qq.com
 * @date 2019-8-6
 */
public class DeptWorklistEditHandlerEx extends EditHandler {
	private static Logger logger = Logger
			.getLogger("com.kingdee.shr.ats.service.DeptWorklistEditHandler");

	private Context ctx;

	public DeptWorklistEditHandlerEx(Context ctx) {
		this.ctx = ctx;
	}

	public DeptWorklistEditHandlerEx() {
		this.ctx = SHRContext.getInstance().getContext();
	}

	StringBuffer sql = new StringBuffer();

	StringBuffer sb = new StringBuffer();

	@SuppressWarnings("unchecked")
	public void getStandardAction(HttpServletRequest request,
			HttpServletResponse response, ModelMap model)
			throws SHRWebException {
		
		String perfmIndicatId = request.getParameter("id");// 负面清单id
		String evaluStandard = null;// 评价标准
		Map map = new HashMap();
		IRowSet rowSet = null;

		if (StringUtils.isEmpty(perfmIndicatId)) {
			logger.error("负面清单项目为空！");
		}

		try {
			rowSet = DbUtil.executeQuery(ctx, joinSql(perfmIndicatId));
			while (rowSet.next()) {
				evaluStandard = rowSet.getString("standard");
				if (!StringUtils.isEmpty(evaluStandard)) {
					map.put("evaluStandard", evaluStandard);
				}
			}
		} catch (BOSException e) {
			logger.error(e.getMessage(), e);
			throw new SHRWebException("获取评价标准失败!", e);
		} catch (SQLException e) {
			logger.error(e.getMessage(), e);
			throw new SHRWebException("获取评价标准失败!", e);
		}
		JSONUtils.SUCCESS(map);
	}
	/**
	 * 
	 * <p>Title: joinSql</p>
	 * <p>Description: 拼接sql，根据负面清单项目带出评价标准</p>
	 * @param perfmIndicatId
	 * @return
	 */
	private String joinSql(String perfmIndicatId) {
		sql
				.append(
						"SELECT CFEvaluationCriterion as standard FROM CT_MAN_AssessmentIndexs")
				.append(" where fid=")

				.append("'" + perfmIndicatId + "'");

		System.out.println("============根据负面清单项目带出评价标准的sql:" + sql.toString()
				+ "===========");

		return sql.toString();
	}

	/**
	 * Title: afterCreateNewModel
	 * Description: 自动带出当前登录人、日期、部门
	 */
	protected void afterCreateNewModel(HttpServletRequest request,
			HttpServletResponse response, CoreBaseInfo coreBaseInfo)
			throws SHRWebException {
		super.afterCreateNewModel(request, response, coreBaseInfo);

		Date nowDate = DateTimeUtils.truncateDate(new Date());
		UserInfo currentUserInfo = ContextUtil.getCurrentUserInfo(this.ctx);
		DeptWorklistInfo info = (DeptWorklistInfo) coreBaseInfo;
		BOSUuid userId = currentUserInfo.getPerson().getId();
		PersonPositionInfo personPositionInfo = SHRBillUtil.getAdminOrgUnit(userId.toString());
		info.setCreator(currentUserInfo);
		info.setBizDate(nowDate);
		info.setAdminOrg(personPositionInfo.getPersonDep());

	}

	/**
	 * 
	 * Title: getAssessmentIndexsAction
	 * Description: 根据部门查询负面清单项目，过滤
	 * @param request
	 * @param response
	 * @param modelMap
	 * @throws SHRWebException
	 */
	public void getAssessmentIndexsAction(HttpServletRequest request,
			HttpServletResponse response, ModelMap modelMap)
			throws SHRWebException {
		UserInfo currentUserInfo = ContextUtil.getCurrentUserInfo(this.ctx);
		BOSUuid userId = currentUserInfo.getPerson().getId();
		PersonPositionInfo personPositionInfo = SHRBillUtil.getAdminOrgUnit(userId.toString());

		String orgId = personPositionInfo.getPersonDep().getId().toString();

		StringBuilder sb = new StringBuilder();
		List<String> orgIds = new ArrayList<String>();
		if (!StringUtils.isEmpty(orgId)) {
			String sql = "select fid from CT_MAN_AssessmentIndexs where CFSubordinateid = '"
					+ orgId + "'";

			System.out.println("获取符合当前登录人部门负面清单" + sql);
			try {
				IRowSet rowSet = DbUtil.executeQuery(ctx, sql);
				while (rowSet.next()) {
					String adminOrgId = rowSet.getString("fid");
					orgIds.add(adminOrgId);
				}
			} catch (BOSException e) {
				e.printStackTrace();
				throw new ShrWebBizException("根据部门查询负面清单项目失败！");
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}

		for (int i = 0; i < orgIds.size(); i++) {
			String orgIdi = orgIds.get(i);
			sb.append(orgIdi);

			if (i < orgIds.size() - 1) {
				sb.append("','");
			}
		}

		modelMap.put("orgIds", sb.toString());
		writeSuccessData(modelMap);

	}
	@Override
	protected void beforeSave(HttpServletRequest request,
			HttpServletResponse response, CoreBaseInfo model)
			throws SHRWebException {
		super.beforeSave(request, response, model);
		DeptWorklistInfo bill = (DeptWorklistInfo) model;
		bill.setBillState(HRBillStateEnum.SAVED);
	}

	/**
	 * Title: beforeSubmit
	 * Description: 提交工作流
	 */
	@Override
	protected void beforeSubmit(HttpServletRequest request,
			HttpServletResponse response, CoreBaseInfo model)
			throws SHRWebException {
		super.beforeSubmit(request, response, model);

		DeptWorklistInfo bill = (DeptWorklistInfo) model;

		String userID = HRFilterUtils.getCurrentUserId(ctx);
		String functionName = "com.kingdee.eas.custom.deptseasonworklist.app.DeptWorklistEditUIFunction";
		String operationName = "actionSubmit";
		try {
			String temp = EnactmentServiceProxy.getEnacementService(ctx)
					.findSubmitProcDef(userID, bill, functionName,
							operationName);
			if ((temp == null) || (temp.trim().equals("")))
				throw new ShrWebBizException("没有可用的部门季度工作目标清单工作流");
		} catch (WfException e) {
			throw new SHRWebException(e.getMessage());
		} catch (BOSException e) {
			throw new SHRWebException(e.getMessage());
		}

		bill.setBillState(HRBillStateEnum.SUBMITED);
		String operateStatus = request.getParameter("operateState");
		if ((StringUtils.isEmpty(operateStatus))
				|| (!("ADDNEW".equalsIgnoreCase(operateStatus)))) {
			return;
		}
		bill.setExtendedProperty("isAddNew", "isAddNew");
	}
}
